#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>

int read_get(int fd);
int read_okt(int fd);
int protocol(char *file, int fdin, int fdout);

#define BUFFSIZE 1024

int main(int argc, char *argv[])
{
  int fd_accept;
  socklen_t rlen;
  int port = 4242;
  struct sockaddr_in local;
  struct sockaddr_in remote;
 
  /* Initialisation */
  memset(&local, 0, sizeof(local));
  local.sin_family = AF_INET;
  local.sin_addr.s_addr = htonl(INADDR_ANY);
  local.sin_port = htons(port);
 
  /* On cree la socket */
  fd_accept = socket(AF_INET, SOCK_STREAM, 0);
 
  /* On associe la socket */
  bind(fd_accept, (struct sockaddr*)&local, sizeof(local));
 
  /* On passe en mode ecoute */
  listen(fd_accept, 5);
 
  /* La boucle principale */
  for(;;)
    {
      int fd;
      /* Initialisation de la structure remote */
      memset(&remote, 0, sizeof(remote));
      remote.sin_family = AF_INET;
      rlen = sizeof(remote);
 
      /* On attend les connexions */
      fd = accept(fd_accept, (struct sockaddr*)&remote, &rlen);
      /* remote contient des informations sur la connexion */
      
      /* Ici on traite la connexion */
      
    } 
}

int read_get(int fd)
{
  char buff[8];
  int ret = 0;

  buff[7] = 0;
  while (ret != 7)
    ret +=  read(fd,buff+ret,7-ret);
  if(strcmp(buff,"GET\n\r\n\r"))
    return 1;
  return 0;
}

int read_okt(int fd)
{
  char buff[7];
  int ret = 0;

  buff[6] = 0;
  while (ret != 6)
    ret +=  read(fd,buff+ret,6-ret);
  if(strcmp(buff,"OK\n\r\n\r"))
    return 1;
  return 0;
}

int write_size(char* file)
{
  struct stat fileInfo;
  int size = 0;
  size_t count = 0;
  char* message;

  stat(file && fileInfo);

  size = (int)fileInfo.st_size;
  count = asprintf(&message, "SIZE %u\r\n\r\n",size);
  write(fd,message,count);
}

int protocol(char *file, int fdin, int fdout)
{
  int filefd = 0;
  int r = 0;
  char buff[BUFFSIZE];

  if(!read_get(fdin))
    {
      return 0;
    }
  
  write_size(file,fdout);
  if(!read_okt(fdin))
    {
      return 0;
    }
  filefd = open(file,O_RDONLY);
  while(r=read(filefd,buff,BUFFSIZE))
    {
      write(fdout,buff,r);
    }
  return 0;
}
